package com.suse.service.community.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.collection.CollectionUtil;
import com.suse.common.util.core.StringUtil;
import com.suse.common.util.io.IoUtil;
import com.suse.service.community.constant.UserConstant;
import com.suse.service.community.entity.User;
import com.suse.service.community.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * 登录前端控制器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-29 20:34
 */
@Slf4j
@Controller
public class LoginController {

    @Resource
    private UserService userService;

    @GetMapping("/register.html")
    public String getRegisterPage() {
        return "site/register";
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/register")
    public String register(Model model, User user) {
        Map<String, Object> map = userService.register(user);
        if (CollectionUtil.isEmpty(map)) {
            model.addAttribute("msg","注册成功，我们已经向您的邮箱发送了一封激活邮件，请尽快激活账号！");
            model.addAttribute("target","/index.html");
            return "site/operate-result";
        }else {
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return "site/register";
        }
    }

    @GetMapping("/login.html")
    public String getLoginPage() {
        return "site/login";
    }

    @GetMapping("/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId") int userId,@PathVariable("code") String code) {
        int res = userService.activation(userId, code);
        if (res == UserConstant.ACTIVATION_SUCCESS) {
            model.addAttribute("msg","激活成功，您的账号可以正常使用了！");
            model.addAttribute("target","/login.html");
        }
        if (res == UserConstant.ACTIVATION_REPEAT) {
            model.addAttribute("msg","无效操作，该账号已经激活过了！");
            model.addAttribute("target","/index.html");
        }
        if (res == UserConstant.ACTIVATION_FAIL) {
            model.addAttribute("msg","激活失败，您提供的激活码不正确！");
            model.addAttribute("target","/index.html");
        }
        return "site/operate-result";
    }

    @GetMapping("/captcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(100,40,4,4);
        String code = circleCaptcha.getCode();
        session.setAttribute("code",code);
        response.setContentType("image/png");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            BufferedImage image = circleCaptcha.getImage();
            ImageIO.write(image,"png",out);
        } catch (IOException e) {
            log.error("获取验证码失败:" + e.getMessage());
        }finally {
            IoUtil.close(out);
        }
    }

    @PostMapping("/login")
    public String login(Model model,User user,String code,boolean remeberme,HttpSession session,HttpServletResponse response) {
        // 验证验证码
        String sessionCode = (String) session.getAttribute("code");
        if (StringUtil.isNotEqualsIgnoreCase(sessionCode,code)) {
            model.addAttribute("codeMsg","验证码输入不正确！");
            return "site/login";
        }
        // 得到登录凭证过期时间
        int expireSeconds = remeberme ? UserConstant.REMEBER_ME_LOGIN_TICKET_EXPIRE : UserConstant.DEFAULT_LOGIN_TICKET_EXPIRE;
        // 登录
        Map<String, Object> map = userService.login(user, expireSeconds);
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", String.valueOf(map.get("ticket")));
            cookie.setPath("");
            cookie.setMaxAge(expireSeconds);
            response.addCookie(cookie);
            return "redirect:/index.html";
        }else {
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            return "site/login";
        }
    }

    @GetMapping("/logout")
    public String logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket);
        return  "redirect:/login.html";
    }

}
